#include <iostream>
#include <websocketpp/server.hpp>
#include <websocketpp/config/asio_no_tls.hpp>

typedef websocketpp::server<websocketpp::config::asio> webserver_t;

void open_callback(webserver_t* wsp, websocketpp::connection_hdl hdl)
{
    std::cout << "ws 握手成功" << std::endl;
}

void close_callback(webserver_t* wsp, websocketpp::connection_hdl hdl)
{
    std::cout << "ws 断开连接" << std::endl;
}

void http_callback(webserver_t* wsp, websocketpp::connection_hdl hdl)
{
    auto conn = wsp->get_con_from_hdl(hdl);
    std::cout << "body: " << conn->get_request_body() << std::endl;
    auto req = conn->get_request();
    std::cout << "request: " << req.get_method() << std::endl;
    std::cout << "uri: " << req.get_uri() << std::endl;

    // std::string send_body = "<html><body><h1>Hello World</h1></body></html>";
    // conn->set_body(send_body);
    conn->set_body(conn->get_request_body());
    conn->append_header("Content-Type", "text/html");
    conn->set_status(websocketpp::http::status_code::ok);
}

void message_callback(webserver_t* wsp, websocketpp::connection_hdl hdl, webserver_t::message_ptr msg)
{
    auto conn = wsp->get_con_from_hdl(hdl);
    std::cout << "wsmsg: " << msg->get_payload() << std::endl;
    std::string respond = "server # " + msg->get_payload();
    conn->send(respond, websocketpp::frame::opcode::text);
}

int main()
{
    // 实例化服务器对象
    webserver_t server;
    // 设置日志等级
    server.set_access_channels(websocketpp::log::alevel::none);
    //设置asio调度器
    server.init_asio();
    server.set_reuse_addr(true);

    //设置回调函数
    server.set_open_handler(std::bind(&open_callback, &server, std::placeholders::_1));
    server.set_http_handler(std::bind(&http_callback, &server, std::placeholders::_1));
    server.set_message_handler(std::bind(&message_callback, &server, std::placeholders::_1, std::placeholders::_2));
    server.set_close_handler(std::bind(&close_callback, &server, std::placeholders::_1));

    //设置监听端口
    server.listen(8080);
    // 开始接收连接
    server.start_accept();
    // 服务器启动
    server.run();

    return 0;
}